package org.lsda.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lsda.sched.LsdaScheduler;
import org.quartz.SchedulerException;

import com.google.gson.JsonObject;

/**
 * Servlet implementation class Scheduler
 */
@WebServlet("/Scheduler")
public class Scheduler extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Scheduler() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String action = request.getParameter("event").trim();
		System.out.println("event="+action);
		boolean ret = false;
		try {
			if ("start".equals(action)) {
				System.out.println("start up");
				startup();
			} else if ("stop".equals(action)) {
				System.out.println("shut down");
				shutdown();
			}
			ret = status();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		JsonObject json = new JsonObject();
		json.addProperty("status", ret);
		json.addProperty("Result", "OK");
		
		PrintWriter writer = response.getWriter();
		System.out.println(json.toString());
		writer.write(json.toString());
	}

	private boolean startup() throws SchedulerException {
		boolean ret = false;
		LsdaScheduler.startup();
		return ret;
	}

	private boolean shutdown() throws SchedulerException {
		boolean ret = false;
		LsdaScheduler.shutdown();
		return ret;
	}

	private boolean status() throws SchedulerException {
		boolean ret = false;
		ret = LsdaScheduler.isUp();
		return ret;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
		// TODO Auto-generated method stub
	}

}
